﻿using System;
using System.Collections.Generic;
using System.Text;
using SuperListEx.Sections;
using System.Drawing;

namespace SuperListEx
{
  /// <summary>
  /// Used by PreviewListStyle
  /// </summary>
  public class MyRowSection : RowSection
  {
    private getPreviewText getText;
    private Rectangle _rect;
    private PreviewStyle _style;

    public MyRowSection(ListControl listControl, RowIdentifier rowIdentifier, HeaderSection headerSection, int position, PreviewStyle style, getPreviewText getText)
      : base(listControl, rowIdentifier, headerSection, position)
    {
      _style = style;
      this.getText = getText;
    }

    private Font AutoPreviewFont
    {
      get
      {
        return new Font(Host.Font, FontStyle.Italic);
      }
    }

    public override bool NeedsLayoutOnSelection
    {
      get
      {
        return _style == PreviewStyle.SelectedOnly;
      }
    }

    public override void Layout(GraphicsSettings gs, Size maximumSize)
    {
      base.Layout(gs, maximumSize);

      if (_style == PreviewStyle.AllRows || IsSelected)
      {
        using (Font autoPreviewFont = AutoPreviewFont)
        {
          int top = Size.Height;
          int autoHeight = autoPreviewFont.Height * 2;
          int indent = IndentWidth + 5;

          if (!string.IsNullOrEmpty(getText.Invoke(this.Item).ToString()))
          {
            _rect = new Rectangle(indent, top, Size.Width - indent - 20, autoHeight);
            Size = new Size(Size.Width, Size.Height + autoHeight + 4);
          }
        }
      }
    }

    public override void Paint(GraphicsSettings gs, Rectangle clipRect)
    {
      base.Paint(gs, clipRect);

      if (_style == PreviewStyle.AllRows || IsSelected)
      {
        using (Font autoPreviewFont = AutoPreviewFont)
        {
          Rectangle rect = _rect;

          rect.Offset(HostBasedRectangle.Location);

          Color color;

          if (IsSelected)
          {
            color = SystemColors.HighlightText;
          }
          else
          {
            color = SystemColors.ControlDarkDark;
          }

          SuperListEx.WinFormsUtility.Drawing.GdiPlusEx.DrawString(gs.Graphics, getText.Invoke(this.Item).ToString(), AutoPreviewFont, color, rect, SuperListEx.WinFormsUtility.Drawing.GdiPlusEx.TextSplitting.MultiLine, SuperListEx.WinFormsUtility.Drawing.GdiPlusEx.Ampersands.Display);
        }
      }
    }
  }
}
